Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Function returning "undefined" while trying to query database in node.js

This piece of code always returns undefined to the calling function. I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me. Any help with this would be highly appreciated. Thank you!

var funcs = require('./index.js');
var connected = require('./database')

query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)


function execute_rows(query){
 con = connected();
 con.query(query, function(err, result, fields) {
     if (err) {
         return console.log(err);
     }
     console.log(result) //Displays correct results
     return result; // Returns undefined to calling function
 })
 con.end();
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Harshith

Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.

The problem with your function is your not actually returning the result "on time". You need to return a promise to get the result from your function.

This could be a little hard to understand when you're new in JS. Your function should be something like this:

function execute_rows(query){
 con = connected();
 return new Promise((resolve, reject) => {
     con.query(query, function(err, result, fields) {
         if (err) {
             // Returning the error
             reject(err);
             con.end();
         }

         resolve(result);
         con.end();
     });
 });
}

Now, when you call you call your function, you have two options:

  1. Use async/await
  2. Still using promises (callback-driven)

Calling your function:

const dbResult = await execute_rows(query);

or

execute_rows(query).then(result => {
    // Get the result
    console.log('result:', result);
}).catch(error => {
    // Get the error
    console.log('error:', error);
});

Please, read about promises and async/await pattern! Links:

Promises: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!